/* 
 * File:   StreamedAudioSource.cpp
 * Author: RedEyedKiller
 * 
 * Created on 18 Δεκέμβριος 2010, 9:28 μμ
 */

#include "StreamSource.h"
#include "OGGStream.h"

namespace al
{

StreamSource::StreamSource(ALuint source) : AbstractALSource(source)
{
    dataStream = NULL;
    numOfLoops = 0;
}

StreamSource::~StreamSource()
{
    dataStream->Release( );
}

bool StreamSource::UpdateStream()
{
    if( GetSourceState( ) == AL_PLAYING && updatable )
    {
        if( dataStream != NULL )
        {
            STREAM_UPDATE_RESULT res = dataStream->Update( sourceId, numOfLoops != 0 );
            if( res == SUR_LOOP )
            {
                --numOfLoops;
            }
            else if( res == SUR_EOF )
            {
                updatable = false;
                this->Stop( );
            }
        }
    }
    else
    {
        int processed;
        //get processed buffers
        alGetSourcei( sourceId, AL_BUFFERS_PROCESSED, &processed );
        if( processed == 2 )
        {
            Stop( );
        }
    }

    return true;
}

void StreamSource::Rewind()
{
    dataStream->Rewind( sourceId );
    this->Play( );
    updatable = true;
}

bool StreamSource::Prepare(const char* name)
{
    if( dataStream != NULL )
    {
        this->Stop();
        dataStream->UnqueueBuffers(sourceId);
        delete dataStream;
    }

    dataStream = new OGGstream;

    if( dataStream->Open( name ) )
    {
        return dataStream->InitializeStream( sourceId );
    }
    return false;
}

}
